package fanketly.core.utils

import android.content.Context
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import androidx.biometric.BiometricManager
import androidx.biometric.BiometricPrompt
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentManager
import com.blankj.utilcode.util.ToastUtils
import com.fanketly.lib_dialog.FingerprintDialogFragment
import java.security.KeyStore
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey

/**
 *Create by Fanketly on 2022/7/10
 *Gitee:https://gitee.com/fanketly
 *desc:
 */
object FingerprintUtils {
    private val DEFAULT_KEY_NAME = "default_key"


    /**
     * 判断是否支持指纹验证
     * */
    fun supportFingerprint(context: Context): Boolean {
        val biometricManager = BiometricManager.from(context)
        when (biometricManager.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_WEAK)) {
            BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE -> {
                ToastUtils.showShort("您的手机不支持指纹功能")
                return false
            }
            BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE -> {
                ToastUtils.showShort("当前不可用")
                return false
            }
            BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED -> {
                ToastUtils.showLong("您至少需要在系统设置中添加一个指纹")
                return false
            }
            BiometricManager.BIOMETRIC_ERROR_SECURITY_UPDATE_REQUIRED -> {}
            BiometricManager.BIOMETRIC_ERROR_UNSUPPORTED -> {}
            BiometricManager.BIOMETRIC_STATUS_UNKNOWN -> {}
            BiometricManager.BIOMETRIC_SUCCESS -> {}
        }
//        context.apply {
//            val keyguardManager = getSystemService(KeyguardManager::class.java)
//            val fingerprintManager = getSystemService(
//                FingerprintManager::class.java
//            )
//            if (!fingerprintManager.isHardwareDetected) {
//                ToastUtils.showShort("您的手机不支持指纹功能")
//                return false
//            } else if (!keyguardManager.isKeyguardSecure) {
//                ToastUtils.showShort("您还未设置锁屏，请先设置锁屏并添加一个指纹")
//                return false
//            } else if (!fingerprintManager.hasEnrolledFingerprints()) {
//                ToastUtils.showLong("您至少需要在系统设置中添加一个指纹")
//                return false
//            }
//        }
        return true
    }

    fun initKey(): KeyStore? {
        try {
            val keyStore = KeyStore.getInstance("AndroidKeyStore")
            keyStore?.load(null)
            val keyGenerator: KeyGenerator =
                KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")
            val builder = KeyGenParameterSpec.Builder(
                DEFAULT_KEY_NAME,
                KeyProperties.PURPOSE_ENCRYPT or
                        KeyProperties.PURPOSE_DECRYPT
            )
                .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
                .setUserAuthenticationRequired(true)
                .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
            keyGenerator.init(builder.build())
            keyGenerator.generateKey()
            return keyStore
        } catch (e: Exception) {
            throw RuntimeException(e)
        }
    }

    /**
     * 如果没有传入keyStore则自动新建
     */
    fun initCipher(keyStore: KeyStore? = null): Cipher {
        try {
            val key: SecretKey =
                (keyStore ?: initKey())?.getKey(DEFAULT_KEY_NAME, null) as SecretKey
            val cipher: Cipher = Cipher.getInstance(
                KeyProperties.KEY_ALGORITHM_AES + "/"
                        + KeyProperties.BLOCK_MODE_CBC + "/"
                        + KeyProperties.ENCRYPTION_PADDING_PKCS7
            )
            cipher.init(Cipher.ENCRYPT_MODE, key)
            return cipher
        } catch (e: Exception) {
            throw RuntimeException(e)
        }
    }

    /**
     * 系统自带验证弹窗
     * */
    fun showBiometricPrompt(activity: FragmentActivity, onSuccess: () -> Unit) {
        BiometricPrompt(activity, object : BiometricPrompt.AuthenticationCallback() {
            override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
                super.onAuthenticationError(errorCode, errString)
                ToastUtils.showShort("验证错误$errString")
            }

            override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
                super.onAuthenticationSucceeded(result)
                onSuccess.invoke()
            }

            override fun onAuthenticationFailed() {
                super.onAuthenticationFailed()
                ToastUtils.showShort("验证失败")
            }
        }).authenticate(BiometricPrompt.PromptInfo.Builder()
            .setTitle("指纹验证")
            .setSubtitle("请把手指放到指纹验证区域")
            .setNegativeButtonText("取消")
            .build())
    }


    /**
     * 显示指纹验证弹窗
     * 如果没有传入cipher则自动新建
     * */
    fun showFingerPrintDialog(
        supportFragmentManager: FragmentManager,
        cipher: Cipher? = null,
        onSuccess: () -> Unit
    ) {
        val fragment = FingerprintDialogFragment(onSuccess)
        fragment.cipher = (cipher ?: initCipher())
        fragment.show(supportFragmentManager, "fingerprint")
    }
}